﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Threading;
using System.IO;
using System.Collections;

namespace CVS_log_parser
{
    public class CvsFileInfoCollection : IEnumerable<CvsFileInfo>
    {
        string[] files;

        class CvsFileInfoCollectionEnumerator : IEnumerator<CvsFileInfo>
        {
            IEnumerator<string> fileEnumerator;

            public CvsFileInfoCollectionEnumerator( IEnumerator<string> fileEnumerator )
            {
                this.fileEnumerator = fileEnumerator;
            }

            public CvsFileInfo Current
            {
                get { return new CvsFileInfo( this.fileEnumerator.Current ); }
            }

            public void Dispose()
            {
                this.fileEnumerator.Dispose();
            }

            object IEnumerator.Current
            {
                get { return this.Current; }
            }

            public bool MoveNext()
            {
                return this.fileEnumerator.MoveNext();
            }

            public void Reset()
            {
                this.fileEnumerator.Reset();
            }
        }

        public CvsFileInfoCollection( string cvsPath, string workPath )
        {
            Process ps = null;
            Environment.CurrentDirectory = Directory.GetParent( workPath ).FullName;

            var psi = new ProcessStartInfo( cvsPath, string.Format( "-Q log \"{0}\"", workPath.Split( new char[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries ).Last() ) ) { RedirectStandardOutput = true, UseShellExecute = false, StandardOutputEncoding = Encoding.GetEncoding( 1251 ) };
            ps = Process.Start( psi );

            var output = ps.StandardOutput.ReadToEnd();

            this.files = new Regex( @"(\?.*\r\n)*\r\n" ).Replace( output, "", 1 ).Split( new string[] { @"=============================================================================

"}, StringSplitOptions.RemoveEmptyEntries ).Where( x => x != Environment.NewLine ).ToArray();
        }

        public IEnumerator<CvsFileInfo> GetEnumerator()
        {
            return new CvsFileInfoCollectionEnumerator( this.files.AsEnumerable().GetEnumerator() );
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return new CvsFileInfoCollectionEnumerator( this.files.AsEnumerable().GetEnumerator() );
        }
    }
}

